<template>
  <div class="page-content pt-48">
    <div class="left">
      <p class="title mb-2">{{ $t('Cambodia_TNAOT') }}</p>
      <p class="tip mb-16">{{ $t('Khmer_information') }}</p>
      <p class="content mb-48">
        {{ $t('tnaot_information') }}
      </p>
      <div class="download">
        <div class="download-img mr-40">
          <div
            v-for="(item, index) in CURRENT_DOWNLOAD_ASSETS"
            :key="index"
            :href="item.url"
            target="_blank"
            :class="{ 'mb-20': index === 0 }"
            @click="download(item)"
          >
            <img class="img img-cover" :src="item.image" />
          </div>
        </div>

        <div class="qr-code">
          <img
            v-if="language == 'zh'"
            class="img img-cover mb-4"
            src="@/assets/images/qr_code_zh.png"
            alt=""
          />
          <img
            v-else
            class="img img-cover mb-4"
            src="@/assets/images/qr_code_km.png"
            alt=""
          />
          <p class="text">{{ $t('Scan_to_download') }}</p>
        </div>
      </div>
    </div>
    <div class="right">
      <img
        v-if="language == 'zh'"
        src="@/assets/images/tnaot_img_cn.png"
        alt=""
      />
      <img v-else src="@/assets/images/tnaot_img_km.png" alt="" />
    </div>
  </div>
</template>

<script>
import { LANGUAGE } from '@/constants/index.js';

const APP_ID = 'com.tnaot.newspro';
const GOOGLE_PLAY_URL = `https://play.google.com/store/apps/details?id=${APP_ID}`;
const APPLE_STORE_URL = 'https://itunes.apple.com/us/app/tnaot/id1296073079';

const DOWNLOAD_ASSETS = {
  zh: [
    {
      type: 'apple',
      url: APPLE_STORE_URL,
      image: require('@/assets/images/apple_store_download_cn.png')
    },
    {
      type: 'local',
      image: require('@/assets/images/local_download_cn.png')
    }
  ],
  km: [
    {
      type: 'apple',
      url: APPLE_STORE_URL,
      image: require('@/assets/images/apple_store_download_km.png')
    },
    {
      type: 'google',
      url: GOOGLE_PLAY_URL,
      image: require('@/assets/images/google_download_km.png')
    }
  ]
};

export default {
  name: 'DownloadPage',

  async asyncData({ $API }) {
    const apkDownloadUrl = await $API.downloadAppAndroid(
      {},
      { resolveWithFullResult: true }
    );

    return {
      apkDownloadUrl
    };
  },

  data() {
    return {
      apkDownloadUrl: '',
      fastestAndroidDownloadUrl: ''
    };
  },

  computed: {
    language() {
      return this.$store.state.app.language;
    },

    CURRENT_DOWNLOAD_ASSETS() {
      return this.language === LANGUAGE.ZH
        ? DOWNLOAD_ASSETS.zh
        : DOWNLOAD_ASSETS.km;
    }
  },

  mounted() {
    this.setFastestDownloadUrl();
  },

  methods: {
    async setFastestDownloadUrl() {
      const image = 'https://apk.tnaot.com/apk/logo.png';
      const downloadUrl = this.apkDownloadUrl;
      const replace = url =>
        url.replace(/^(https?:\/\/)?([^\.]+)([^\/]+)/, '$1$21$3');
      const imageB = replace(image);
      const result = await this.getFastestImageUrl(image, imageB);
      this.fastestAndroidDownloadUrl =
        result === imageB ? replace(downloadUrl) : downloadUrl;
    },

    getFastestImageUrl(...srcList) {
      let resolved = false;
      let errorCounter = 0;
      return new Promise((resolve, reject) => {
        srcList.forEach(src => {
          const img = new Image();
          img.onload = () => {
            if (resolved) return;
            resolved = true;
            resolve(src);
          };
          img.onerror = error => {
            errorCounter += 1;
            if (errorCounter === srcList.length) reject('all src failed');
          };
          img.src = src;
        });
      });
    },

    download({ type, url }) {
      switch (type) {
        case 'local':
          window.location.href =
            this.fastestAndroidDownloadUrl || this.apkDownloadUrl;
          break;
        default:
          window.location.href = url;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~assets/styles/variable.scss';

.page-content {
  width: $page-width;
  margin: 0 auto;
  display: flex;

  .left {
    width: 604px;
    padding: 8px 0 0 16px;
    margin-right: 56px;

    .title {
      font-size: 28px;
      color: #0c0c1c;
      letter-spacing: 0;
      line-height: 48px;
      font-weight: 500;
    }

    .tip {
      font-size: 14px;
      color: rgba(12, 12, 28, 0.7);
      letter-spacing: 0;
      line-height: 20px;
    }

    .content {
      font-size: 16px;
      color: #0c0c1c;
      letter-spacing: 0;
      line-height: 28px;
    }

    .download {
      display: flex;
      height: 100px;

      .download-img {
        .img {
          width: 160px;
          height: 40px;
        }
      }

      .qr-code {
        .img {
          width: 80px;
          height: 80px;
        }
        .text {
          font-size: 12px;
          color: #0c0c1c;
          letter-spacing: 0;
          text-align: center;
          line-height: 16px;
        }
      }
    }
  }

  .right {
    width: 404px;
    margin-right: 16px;
  }
}
</style>
